//
//  ExpenditureDetailTableViewController.m
//  dangdang
//
//  Created by air on 16/1/19.
//  Copyright © 2016年 luweijie. All rights reserved.
//

#import "ExpenditureDetailTableViewController.h"
#import "DetailsViewController.h"
#import "MJRefresh.h"
#import "ExpenditureDetailTableViewCell.h"
#import "BillDetailsObject.h"

@interface ExpenditureDetailTableViewController ()

@property (nonatomic, strong) UIRefreshControl * refresh;
@property (nonatomic, strong) NSArray * orderCountArray;
@property (nonatomic, strong) NSMutableArray * orderDetailsArray;
@property (nonatomic, strong) NSDictionary * dic;
@property (nonatomic) BOOL pullDown;
@property (nonatomic) BOOL pullUp;
@property (nonatomic) NSInteger page;

@end

@implementation ExpenditureDetailTableViewController

- (instancetype)init {
    UIStoryboard *sb = [UIStoryboard storyboardWithName:@"ExpenditureDetailTableViewController" bundle:nil];
    self = [sb instantiateViewControllerWithIdentifier:@"ExpenditureDetailTableViewController"];
    return self;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.tableView.rowHeight = UITableViewAutomaticDimension;
    self.tableView.estimatedRowHeight = 44.0;
    
    [self initialization];
    
    [self connection];
    
    [self setupRefresh];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (void)initialization{
    _orderDetailsArray = [NSMutableArray new];
    _page = 1;
    
    _pullDown = NO;
    _pullUp = NO;
}

- (void)connection{
    NSString * token = userObject.accessToken;
    NSString * userIDString = userObject.userID;
    NSString * pageString = @"0";
    NSString * pageSizeString = @"30";
    NSString * typeString = @"1";
    
    NSMutableDictionary *params = [[NSMutableDictionary alloc]init];
    [params setObject:token forKey:@"token"];
    [params setObject:userIDString forKey:@"uid"];
    [params setObject:pageString forKey:@"page"];
    [params setObject:pageSizeString forKey:@"pagesize"];
    [params setObject:typeString forKey:@"type"];
    
    [self postRequestWithMethodName:@"bills/get_bills" andParams:params andSender:nil];
}

//上拉刷新
- (void)setupFooterRefresh{
    _pullUp = YES;
    
    __unsafe_unretained __typeof(self) weakSelf = self;
    
    // 设置回调（一旦进入刷新状态就会调用这个refreshingBlock）
    self.tableView.mj_footer = [MJRefreshAutoNormalFooter footerWithRefreshingBlock:^{
        [weakSelf loadMoreData];
    }];
}

#pragma mark 上拉加载更多数据
- (void)loadMoreData
{
    _pullUp = YES;
    
    NSString * token = userObject.accessToken;
    NSString * userIDString = userObject.userID;
    NSString * pageString = [NSString stringWithFormat:@"%ld", (long)_page];
    NSString * pageSizeString = @"30";
    NSString * typeString = @"1";
    
    NSMutableDictionary *params = [[NSMutableDictionary alloc]init];
    [params setObject:token forKey:@"token"];
    [params setObject:userIDString forKey:@"uid"];
    [params setObject:pageString forKey:@"page"];
    [params setObject:pageSizeString forKey:@"pagesize"];
    [params setObject:typeString forKey:@"type"];
    
    [self postRequestWithMethodName:@"bills/get_bills" andParams:params andSender:nil];
}

/**
 *  集成下拉刷新
 */
-(void)setupRefresh
{
    self.refresh = [[UIRefreshControl alloc]init];
    //刷新图形颜色
    self.refresh.tintColor = [UIColor lightGrayColor];
    //刷新的标题
    self.refresh.attributedTitle = [[NSAttributedString alloc] initWithString:@"下拉刷新"];
    
    [self.refresh addTarget:self action:@selector(refreshStateChange:) forControlEvents:UIControlEventValueChanged];
    
    [self.tableView addSubview:self.refresh];
}

/**
 *  UIRefreshControl进入刷新状态：加载最新的数据
 */
-(void)refreshStateChange:(UIRefreshControl *)control
{
    if (control.refreshing) {
        _pullDown = YES;
        _page = 1;
        
        control.attributedTitle = [[NSAttributedString alloc]initWithString:@"正在刷新"];
        
        NSString * token = userObject.accessToken;
        NSString * userIDString = userObject.userID;
        NSString * pageString = @"0";
        NSString * pageSizeString = @"30";
        NSString * typeString = @"1";
        
        NSMutableDictionary *params = [[NSMutableDictionary alloc]init];
        [params setObject:token forKey:@"token"];
        [params setObject:userIDString forKey:@"uid"];
        [params setObject:pageString forKey:@"page"];
        [params setObject:pageSizeString forKey:@"pagesize"];
        [params setObject:typeString forKey:@"type"];
        
        [self postRequestWithMethodName:@"bills/get_bills" andParams:params andSender:nil];
    }
}

#pragma mark - Table view data source

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    
    return _orderDetailsArray.count;
}


- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    ExpenditureDetailTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"expenditureIdentifier" forIndexPath:indexPath];
    
    BillDetailsObject * billObject = [[BillDetailsObject alloc] init];
    billObject = _orderDetailsArray[indexPath.row];
    cell.moneyLabel.text = billObject.amount;
    cell.idLabel.text = billObject.billId;
    
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    
    return cell;
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    return 0.1f;
}

//- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
//    DetailsViewController * detailsboardVC = [[UIStoryboard storyboardWithName:@"DetailsViewController" bundle:nil] instantiateViewControllerWithIdentifier:@"DetailsViewController"];
//
//    [self.navigationController pushViewController:detailsboardVC animated:YES];
//}

#pragma-mark AFNetWorking

-(void)postRequestWithMethodName:(NSString *)methodName andParams:(NSDictionary *)params andSender:(id)sender
{
    NSString *requestString = [NSString stringWithFormat:@"%@%@",URLDoman,methodName];
    AFHTTPSessionManager *session = [AFHTTPSessionManager manager];
    session.responseSerializer = [AFHTTPResponseSerializer serializer];
    session.requestSerializer.timeoutInterval = TimeoutInterval;
    
    __weak typeof(self) weakSelf = self;
    if (requestString.length > 0 && requestString != nil) {
        [session POST:requestString parameters:params success:^(NSURLSessionDataTask * _Nonnull task, id  _Nonnull responseObject) {
            NSError *jsonError = nil;
            id dict = [NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingMutableContainers error:&jsonError];
            if (jsonError != nil) {
                NSLog(@"json解析失败");
            }
            
            NSMutableDictionary *senderDic;
            if ([sender isKindOfClass:[NSDictionary class]]) {
                senderDic = [NSMutableDictionary dictionaryWithDictionary:sender];
            }
            else{
                senderDic = [NSMutableDictionary new];
            }
            [senderDic setObject:methodName forKey:TYPE];
            NSLog(@"dict = %@", dict);
            
            [LoadingView hideWithAnimated:YES];
            [weakSelf requestSuccessedWithResult:dict NSURLSessionTask:task sender:sender];
            
        } failure:^(NSURLSessionDataTask * _Nonnull task, NSError * _Nonnull error) {
            NSLog(@"error = %@", error);
            [weakSelf requestFailureWithNSURLSessionTask:task error:error sender:sender];
            [LoadingView hideWithAnimated:YES];
        }];
    }
}

//网络连接返回数据
- (void)requestSuccessedWithResult:(id)result NSURLSessionTask:(NSURLSessionTask *)task sender:(id)sender{
    
    NSString * urlString = [NSString stringWithFormat:@"%@", task.currentRequest.URL];
    
    if ([result isKindOfClass:[NSDictionary class]]) {
        NSString * code = [NSString stringWithFormat:@"%@", [result objectForKey:@"retcode"]];
        if ([urlString isEqualToString:[NSString stringWithFormat:@"%@%@", URLDoman, @"bills/get_bills"]]){
            if ([code isEqualToString:@"0"]) {
                NSArray * arrayCount = [result objectForKey:@"retmsg"];
                if (arrayCount.count == 0 && _pullDown == YES) {
                    self.refresh.attributedTitle = [[NSAttributedString alloc] initWithString:@"全部加载完毕"];
                    [self.refresh endRefreshing];
                    _pullDown = NO;
                }else if (!(arrayCount.count == 0) && _pullDown == YES){
                    _orderDetailsArray = [NSMutableArray new];
                    _orderCountArray = [result objectForKey:@"retmsg"];
                    
                    for (int i = 0; i < _orderCountArray.count; i ++) {
                        BillDetailsObject * billObject = [[BillDetailsObject alloc] init];
                        _dic = _orderCountArray[i];
                        billObject.amount = [NSString stringWithFormat:@"%@", [_dic objectForKey:@"amount"]];
                        billObject.billId = [NSString stringWithFormat:@"%@", [_dic objectForKey:@"id"]];
                        billObject.remark = [NSString stringWithFormat:@"%@", [_dic objectForKey:@"remark"]];
                        billObject.rtime = [NSString stringWithFormat:@"%@", [_dic objectForKey:@"rtime"]];
                        billObject.type = [NSString stringWithFormat:@"%@", [_dic objectForKey:@"type"]];
                        
                        [_orderDetailsArray addObject:billObject];
                    }
                    [self.refresh endRefreshing];
                    
                    [self.tableView reloadData];
                    
                    [self setupFooterRefresh];
                    
                    _pullDown = NO;
                }else if (!(arrayCount.count == 0) && _pullUp == YES){
                    _orderCountArray = [result objectForKey:@"retmsg"];
                    for (int i = 0; i < _orderCountArray.count; i ++) {
                        BillDetailsObject * billObject = [[BillDetailsObject alloc] init];
                        _dic = _orderCountArray[i];
                        billObject.amount = [NSString stringWithFormat:@"%@", [_dic objectForKey:@"amount"]];
                        billObject.billId = [NSString stringWithFormat:@"%@", [_dic objectForKey:@"id"]];
                        billObject.remark = [NSString stringWithFormat:@"%@", [_dic objectForKey:@"remark"]];
                        billObject.rtime = [NSString stringWithFormat:@"%@", [_dic objectForKey:@"rtime"]];
                        billObject.type = [NSString stringWithFormat:@"%@", [_dic objectForKey:@"type"]];
                        
                        [_orderDetailsArray addObject:billObject];
                    }
                    _page ++;
                    [self.tableView.mj_footer endRefreshing];
                    [self.tableView reloadData];
                    
                    _pullUp = NO;
                }else if (arrayCount.count == 0 && _pullUp == YES){
                    [self.tableView.mj_footer endRefreshingWithNoMoreData];
                    
                    _pullUp = NO;
                }else if (!(arrayCount.count == 0)){
                    _orderCountArray = [result objectForKey:@"retmsg"];
                    for (int i = 0; i < _orderCountArray.count; i ++) {
                        BillDetailsObject * billObject = [[BillDetailsObject alloc] init];
                        _dic = _orderCountArray[i];
                        billObject.amount = [NSString stringWithFormat:@"%@", [_dic objectForKey:@"amount"]];
                        billObject.billId = [NSString stringWithFormat:@"%@", [_dic objectForKey:@"id"]];
                        billObject.remark = [NSString stringWithFormat:@"%@", [_dic objectForKey:@"remark"]];
                        billObject.rtime = [NSString stringWithFormat:@"%@", [_dic objectForKey:@"rtime"]];
                        billObject.type = [NSString stringWithFormat:@"%@", [_dic objectForKey:@"type"]];
                        
                        [_orderDetailsArray addObject:billObject];
                    }
                    [self.tableView reloadData];
                    
                    [self setupFooterRefresh];
                }
            }else{
                if (_pullUp == YES) {
                    [self.tableView.mj_footer endRefreshing];
                }else if (_pullDown == YES){
                    [self.refresh endRefreshing];
                }
            }
        }
    }
}

- (void)requestFailureWithNSURLSessionTask:(NSURLSessionTask *)task error:(NSError *)error sender:(id)sender
{
    //    if (_pullUp == YES) {
    //        [_inProgressTableView.mj_footer endRefreshing];
    //    }else if (_pullDown == YES){
    //        [self.refresh endRefreshing];
    //    }
}

/*
 // Override to support conditional editing of the table view.
 - (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath {
 // Return NO if you do not want the specified item to be editable.
 return YES;
 }
 */

/*
 // Override to support editing the table view.
 - (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath {
 if (editingStyle == UITableViewCellEditingStyleDelete) {
 // Delete the row from the data source
 [tableView deleteRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationFade];
 } else if (editingStyle == UITableViewCellEditingStyleInsert) {
 // Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view
 }
 }
 */

/*
 // Override to support rearranging the table view.
 - (void)tableView:(UITableView *)tableView moveRowAtIndexPath:(NSIndexPath *)fromIndexPath toIndexPath:(NSIndexPath *)toIndexPath {
 }
 */

/*
 // Override to support conditional rearranging of the table view.
 - (BOOL)tableView:(UITableView *)tableView canMoveRowAtIndexPath:(NSIndexPath *)indexPath {
 // Return NO if you do not want the item to be re-orderable.
 return YES;
 }
 */

/*
 #pragma mark - Navigation
 
 // In a storyboard-based application, you will often want to do a little preparation before navigation
 - (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
 // Get the new view controller using [segue destinationViewController].
 // Pass the selected object to the new view controller.
 }
 */

@end
